<template>
  <div>
    <u-form-grid :data="formGrid" ref="child">></u-form-grid>

    <Modal
      v-model="showSelectedGoods"
      title="活动中商品"
      width="900"
      class-name="selectGoodsInfo">
      <u-form-grid :data="formGoodsGrid" :filterParams="formGoodsGridParams" ref="goods"></u-form-grid>
      <div slot="footer">
      </div>
    </Modal>
    <select-goods-info v-show="showSelectGoodsInfo" @selectOk="selectOk"></select-goods-info>


  </div>
</template>

<script>
  import values from '../../utils/values'
  import moment from "moment";
  import SelectGoodsInfo from "../goods/SelectGoodsInfo.vue";
  import axios from "axios";

  export default {
    //限时折扣活动
    name: 'DiscountActivity',
    components: {
      "SelectGoodsInfo": SelectGoodsInfo,
    },
    data() {
      let sn = new moment().format("YYYYMMDDhhmm");
      return {
        //显示选择商品界面
        showSelectGoodsInfo: false,
        showSelectedGoods: false,
        //
        goodsInfoId: null,

        formGoodsGridParams: {
          activityFullPathIds: null
        },
        formGoodsGrid: {
          options: {
            version: 'v2',
            autoLoad: false,
            url: {
              page: "/goodsInfo/activity/page",
            }
          },
          form: {},
          toolbar: {
            create: {
              show: false
            },
            delete: {
              show: false
            },

            button: [
              {
                theme: "error", show: true, label: "删除", loading: false, click: (selections) => {
                console.log("===================");
                this.deleteGoods(selections);
              }
              },
              {
                theme: "success", label: "添加活动商品", icon: "plus", click: (selections) => {
                console.log("===================");
                this.showSelectGoodsInfo = true;
              }
              }],
          },
          table: {
            operation: {
              primaryKey: "id",
              show: false
            },
            columns: [
              {title: 'id', key: 'id'},
              {title: '商品名称', key: 'name'},
              {title: '品牌名称', key: 'brandName'},
              {title: '商品属性', key: 'goodsType'},
              {title: '参加的活动', key: 'activityFullPathName'},
            ]
          }
        },


        formGrid: {
          options: {
            version: 'v2',
            url: {
              page: "/activities/discountPage",
              save: "/activities/save",
              delete: "/activities/delete",
            }
          },
          tips: {title: "限时折扣活动", content: "可以新建和编辑限时折扣活动。活动开始时间后，就会自动上架，优惠方式为打折或者直接减去价格二选一"},
          toolbar: {
            button: [
              {
                theme: "success", label: "清空活动缓存", icon: "plus", click: (selections) => {
                this.$Modal.confirm({
                  title: "提示", "content": "确定清空吗?", onOk: () => {
                    this.clearCache();
                  }
                });
              }
              }
            ],
          },
          form: {
            modal: {
              title: "限时折扣活动"
            },
            columns: [
              {label: "活动名称", type: "text", name: "name", required: true},
              {
                label: "活动编号", type: "text", name: "sn", required: true, init: sn, edit: {
                show: true, disabled: true
              },
              },
              {label: "开始时间", type: "datetime", name: "startTime"},
              {label: "结束时间", type: "datetime", name: "endTime"},
              {label: "折扣", type: "text", name: "discountValue", init: 0},
              {label: "支付金额(单位:元)", type: "text", name: "discountMinusPrice", init: 0},
              {label: "限购方式", type: "select", name: "limitType", required: true, data: values.limitType},
              {label: "限购份数", type: "text", name: "limitCopies", init: 0},
              {label: "库存扣减", type: "select", name: "stockCountType", required: true, data: [{name: '活动', value: '活动'}, {name: '商品', value: '商品'}, {name: '规格', value: '规格'}, {name: '规格代码', value: '规格代码'}], init: {name: '规格', value: '规格'}},
              {label: "折扣原价", type: "text", name: "discountOriginPrice", init: 0},
              {label: "库存数量", type: "text", name: "seckillProvideCopies", init: 0},
              {label: "活动状态", type: "select", name: "status", required: true, data: values.activityStatus, colNumber: 12, init: {name: '开启中', value: '开启中'}},
              {label: "活动规则", type: "textarea", name: "ruleDesc"},
            ],
            submitBefore: (data) => {
              data["type"] = "限时折扣";
              let stockCountType = data["stockCountType"];//活动 seckillProvideCopies必填并且大于0
              let seckillProvideCopies = data["seckillProvideCopies"];
              let discountMinusPrice = data["discountMinusPrice"];//以下必填其一
              let discountOriginPrice = data["discountOriginPrice"];//以下必填其一
              let discountValue = data["discountValue"];
              if (stockCountType === '活动' && seckillProvideCopies < 1) {
                this.$Message.info({content: "库存扣减为「活动」库存数量必填并大于0"});
                return false;
              }
              if (stockCountType === '活动' && !discountOriginPrice) {
                this.$Message.info({content: "库存扣减为「活动」折扣原价不能为空"});
                return false;
              }
              if (discountValue < 1 && discountMinusPrice < 1) {
                this.$Message.info({content: "折扣，支付金额必填，并大于0"});
                return false;
              }
              return true;
            }
          },
          table: {
            operation: {
              primaryKey: "id",
              buttons: [
                {
                  key: "view", show: true, "label": "查看", "theme": "text", click: (row, index, _this) => {
                  _this.optViewClick(row, index);
                }
                },
                {
                  key: "goods", show: true, "label": "关联产品", "theme": "warning", click: (row, index, _this) => {
                  this.formGoodsGridParams.activityFullPathIds = row.id;
                  this.showSelectedGoods = true;
                  setTimeout(() => this.$refs.goods.$emit('reloadData'));
                }
                },
                {
                  key: "edit", show: true, "label": "编辑", "theme": "primary", click: (row, index, _this) => {
                  _this.optEditClick(row, index);
                }
                },
                {
                  key: "delete", show: true, "label": "删除", "theme": "error", click: (row, index, _this) => {
                  _this.optDeleteClick(row, index);
                }
                }
              ],
              column: {
                title: '操作',
                key: 'action',
                className: 'optColumn',
                width: 220,
              },
            },
            columns: [
              {title: '活动名称', key: 'name'},
              {title: '活动编号', key: 'sn',renderType:"tooltip"},
              {title: '限购方式', key: 'limitType',renderType:"tooltip"},
              {title: '限购份数', key: 'limitCopies'},
              {title: '活动状态', key: 'status'},
            ]
          }
        }
      }
    },
    methods: {
      selectOk(goods) {
        console.log("选择的商品:%o", goods);
        //调用方法时传递参数
        this.showSelectGoodsInfo = false;

        if (!goods || goods.length <= 0) {
          this.$Message.info({content: "请选择参加活动的商品"});
          return;
        }
        let ids = [];
        for (let item of goods) {
          ids.push(item.id);
        }

        let params = {
          id: this.formGoodsGridParams.activityFullPathIds,
          goodsIds: ids
        };

        axios.post("/activities/goods/save", params).then(response => {
          this.$Message.success('保存成功');
          setTimeout(() => this.$refs.goods.$emit('reloadData'));
        }).catch(response => {

        })
      },
      deleteGoods(selections) {
        console.log("selections: %o", selections);
        let params = [];
        for (let item of selections) {
          params.push(item.id);
        }
        axios.post("/goodsInfo/activity/free", params).then(response => {
          this.$Message.success('释放成功');
          setTimeout(() => this.$refs.goods.$emit('reloadData'));
        }).catch(response => {

        })
      },
      clearCache() {
        //初始化销售区域数据
        axios.post("/activities/clearCache").then(response => {
          this.$Notice.success({"title": "提示", "desc": "缓存清空成功！"});
        });
      }
    }
  }
</script>
<style>
  .selectGoodsInfo {
    z-index: 2002;
  }
</style>
